from time import gmtime, strftime, strptime
from datetime import date, timedelta
import time, Xml, os, InterfaceRB, InterfaceExt

def ExcludeCleanup(boundaryEnd):
    """Check last backup for each file and launch cleanup if safe"""
    
    list = Xml.retrieveAllXml('C:\\Program Files\\EasyBackupTool\\BackupTimes.xml')
    listOfCleanup = []
    for element in list:
        splitUnderscore = element.split('_')
        splitAt = splitUnderscore[-1].split('@')
        lastBackupDate = strptime(splitAt[0], "%d-%m-%Y")
        #print lastBackupDate
        #print strptime(boundaryEnd, "%d-%m-%Y")
        if lastBackupDate > strptime(boundaryEnd, "%d-%m-%Y"):
            # safe to cleanup
            listOfCleanup.append(splitUnderscore[0]) 
    return listOfCleanup

def Clean(listValid, boundaryBegin, boundaryEnd):
    """Delete All of month but last"""

    list = Xml.retrieveInfoXml('C:\\Documents and Settings\\All Users\\Application Data\\EBT\\EBT-setup.xml', 'BackupDir')
    listBackup=os.listdir(list[0])
    
    bool=False
    
    listCleanup = []
    for element in listBackup:
        splitExtention =  element.split('.')
        if splitExtention[-1] == 'acl' or splitExtention[-1] == 'xdelta':
            # take care of not taking initial file
            splitUnderscore = element.split('_')
            if splitUnderscore[0] in listValid:
                #take care of taking only safe files to delete (Safe = not most recent backup file)
                splitAt = splitUnderscore[-1].split('@')
                lastBackupDate = strptime(splitAt[0], "%d-%m-%Y")
                if (lastBackupDate == strptime(boundaryBegin, "%d-%m-%Y")) and (lastBackupDate == strptime(boundaryEnd, "%d-%m-%Y")) :
                    #check that the file we will delete are set to be higher than the minimal boundary
                    listCleanup.append(element)
    
    for elements in listValid:
        latestOfDayDelta = InterfaceRB.getClosestAclDate(elements, boundaryEnd+'@23h59m59s', 'xdelta')
        latestOfDayACL = InterfaceRB.getClosestAclDate(elements, latestOfDayDelta)
        if latestOfDayDelta != '01-01-1901@01h01m01s':
            reconstructDelta = elements + '_' + latestOfDayDelta + '.xdelta'
            reconstructACL = elements + '_' + latestOfDayACL + '.acl'
            if reconstructDelta in listCleanup:
                listCleanup.remove(reconstructDelta)
            if reconstructACL in listCleanup:
                listCleanup.remove(reconstructACL)
        else:
            bool=True
            for elem in listCleanup:
                listCleanup.remove(elem)
    
    if bool==True:
        print 'Impossible - Cleanup has already been done, or not possible yet'
    else:
        InterfaceExt.deleteFileH(listCleanup)
#    print listCleanup     
         

def DailyCleanup(dayNumber=time.strftime("%d"), monthNumber=time.strftime("%m"), yearNumber=time.strftime("%Y")):
    """Keep only last backup of previous day"""
    if dayNumber != '1':
        dayNumber = str(int(dayNumber)-1)
        dateSafe= dayNumber+'-'+monthNumber+'-'+yearNumber
        #print dateSafe
        res = ExcludeCleanup(dateSafe)
        Clean(res, dateSafe, dateSafe)
    #print res
    #Clean(res, bound[0], bound[-1])

#if __name__ == "__main__":
#    print time.strftime("%m-%Y")
#    DailyCleanup('14')
    
    